package com.example.student.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.student.entity.MyClass;
import com.example.student.generated.entity.Student;
import com.example.student.service.MyClassService;
import com.example.student.service.MyStudentService;
import com.exmaple.result.PageReq;
import com.exmaple.result.PageReqUnderCondition;
import com.exmaple.result.PageRes;
import com.exmaple.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.exmaple.result.ErrorCode.*;
import static com.exmaple.result.PageRes.success;

@Slf4j
@RestController
@RequestMapping(value = "/student")
public class StudentController {
    @Resource
    private MyStudentService myStudentService;

    @Resource
    private MyClassService myClassService;
    /**
     * 根据学生ID查找
     * @param id
     * @return (success)    、(failure)空
     */
    @GetMapping("/{id}")
    public Result<Student> getId(@PathVariable Long id)
    {
        Student student = myStudentService.getById(id);
        return student!=null?Result.success(student):Result.error(USER_ERROR_A0402);
    }

    /**
     * 根据学生姓名查找多个
     * @param name
     * @return (success)    、(failure)空
     */
    @GetMapping("/some")
    public Result<List<Student>> getSome(@RequestParam String name)
    {
        List<Student> studentList = myStudentService.lambdaQuery().like(StringUtils.isNotBlank(name), Student::getStuName, name).list();
        return studentList.isEmpty()? Result.error(USER_ERROR_A0201): Result.success(studentList);
    }

    /**
     * 查找全部学生
     * @return 全部学生
     */
    @GetMapping("/all")
    public Result<List<Student>> getAll()
    {
        List<Student> studentList = myStudentService.list();
        return studentList.size()==0? Result.error(USER_ERROR_A0201): Result.success(studentList);
    }

    /**
     * 根据学生姓名分页查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public PageRes<Student> getPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(required = false) String name)
    {
        List<Student> studentList= new ArrayList<>();
        //无条件分页查询
        if (name.isEmpty())
        {
            PageReq pageReq=new PageReq();
            pageReq.setPageNum(pageNum);
            pageReq.setPageSize(pageSize);
            Page<Student> studentPage = new Page<>(pageReq.getPageNum(), pageReq.getPageSize());
            studentList = myStudentService.page(studentPage).getRecords();
        }
        //根据学生姓名分页查询
        else
        {
            PageReqUnderCondition pageReq=new PageReqUnderCondition();
            pageReq.setPageNum(pageNum);
            pageReq.setPageSize(pageSize);
            pageReq.setCondition1(name);
            Page<Student> studentPage = new Page<>(pageReq.getPageNum(), pageReq.getPageSize());
            studentList = myStudentService.lambdaQuery()
                                                        .like(StringUtils.isNotBlank(pageReq.getCondition1()),Student::getStuName,pageReq.getCondition1())
                                                        .page(studentPage)
                                                        .getRecords();
        }
        return studentList.isEmpty()?PageRes.error(USER_ERROR_A0201):PageRes.success(Integer.toUnsignedLong(studentList.size()),studentList);
    }

    /**
     * 创建单个学生记录
     * @param stu
     * @return  (success)添加成功、(failure)添加失败
     */
    @PostMapping("/one")
    public Result<String> postOne(@RequestBody Student stu)
    {
        if (myStudentService.getById(stu.getId())==null)
        {
            myStudentService.save(stu);
            myClassService.lambdaUpdate().eq(MyClass::getId,stu.getClassId()).setSql("stu_num=stu_num+1").update();
            return Result.success();
        }
        else
        {
            return Result.error(USER_ERROR_0001);
        }

    }

    /**
     * @param studentList
     * @return  (success)添加成功、(failure)返回添加失败的学生 id
     */
    /**
     * 创建多个学生记录
     * @param studentList
     * @return 返回添加成功的学生的id
     */
    @PostMapping("/batch")
    public Result<String> postBatch(@RequestBody List<Student> studentList)
    {
        StringBuilder res=new StringBuilder();
        for (Student student : studentList)
        {
            if (myStudentService.getById(student.getId())==null)
            {
                myStudentService.save(student);
                myClassService.lambdaUpdate().eq(MyClass::getId,student.getClassId()).setSql("stu_num=stu_num+1").update();
                res.append(student.getId()).append(" ");
            }
        }
        String s = res.toString();
        return s.isEmpty()?Result.error(USER_ERROR_0001):Result.success(s);
    }

    /**
     * 修改单个学生的信息
     * @param stu
     * @return (success)修改成功 ， (failure)修改失败
     */
    @PutMapping("/one")
    public Result<String> putOne(@RequestBody Student stu)
    {
        boolean flag = myStudentService.lambdaUpdate().eq(Student::getId, stu.getId()).update(stu);
        if (flag)
        {
            myClassService.lambdaUpdate().eq(MyClass::getId,stu.getClassId()).setSql("stu_num=stu_num+1").update();
            return Result.success();
        }

        return Result.error(USER_ERROR_0001);
    }

    /**
     * 批量修改学生的全部信息
     * @param studentList
     * @return 返回修改不成功的学生id
     */
    @PutMapping("/batch")
    public Result<String> putBatch(@RequestBody List<Student> studentList)
    {
        StringBuilder res=new StringBuilder();
        for (Student student : studentList) {
            boolean flag = myStudentService.lambdaUpdate().eq(Student::getId,student.getId()).update(student);
            if (flag)
            {
                res.append(student.getId());
                res.append(" ");
                myClassService.lambdaUpdate().eq(MyClass::getId,student.getClassId()).setSql("stu_num=stu_num+1").update();
            }
        }
        String s=res.toString();
        return s.isEmpty()?Result.error(USER_ERROR_0001):Result.success(s);
    }

    /**
     * 删除学生以及其选课记录
     * @param id
     * @return (success)删除成功 (failure)删除失败
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteId(@PathVariable Long id)
    {
        return myStudentService.deleteOne(id)?Result.success():Result.error(USER_ERROR_A1001);
    }

    /**
     * 批量删除学生以及其选课记录
     * @param studentList
     * @return (success )返回删除成功的学生Id
     */
    @DeleteMapping("/batch")
    public Result<String> deleteBatch(@RequestBody List<Student> studentList)
    {
        String s = myStudentService.deleteBatch(studentList);
        return s.isEmpty()? Result.error(USER_ERROR_A1001): Result.success(s);
    }
}
